using System;
using System.Collections.Generic;
using System.Text;
using CMS.BIZ;
using AAM.DAL;
using AAM.BIZ;
using AAM.SQL;

namespace CMS.BOP
{
    public class SqlBizMessageStateProvider : SqlBizObjectProvider<BizMessageState>
    {

        public static readonly string TableAlias = GetTableAlias();
        public static readonly string TableName = GetTableName() + " " + TableAlias;
        public static readonly string AllRows = GetAllRows(TableAlias);

        public BizMessageState Read(int messageId, int memberId)
        {
            return Read(new ObjectID(BizMessageState.ObjectType,new object[]{ messageId,memberId}));
        }
        public bool Delete(int messageId, int memberId)
        {
            return Delete(new ObjectID(BizMessageState.ObjectType, new object[] { messageId, memberId }));
        }

        public List<BizMessageState> ReadAllWithMessageByMember(int memberId, int messageState, int? folderId)
        {

            Command command = null;
            if (folderId != null)
            {
                command = Connection.CreateCommand("SELECT " + AllRows.Replace(TableAlias + ".MessageID, ", "") + ", " + SqlBizMessageProvider.AllRows + " FROM " + TableName + ", " + SqlBizMessageProvider.TableName + " " +
                "WHERE " + TableAlias + ".MemberID=? AND " + TableAlias + ".MessageFolder=? AND " + TableAlias + ".MessageState=? AND " + SqlBizMessageProvider.TableAlias + ".MessageID=" + TableAlias + ".MessageID");
                command.AddParameter(memberId);
                command.AddParameter(folderId);
                command.AddParameter(messageState);
            }
            else
            {
                command = Connection.CreateCommand("SELECT " + AllRows.Replace(TableAlias+".MessageID, ", "") + ", " + SqlBizMessageProvider.AllRows + " FROM " + TableName + ", " + SqlBizMessageProvider.TableName + " " +
                "WHERE " + TableAlias + ".MemberID=? AND " + TableAlias + ".MessageFolder IS NULL AND " + TableAlias + ".MessageState=? AND " + SqlBizMessageProvider.TableAlias + ".MessageID=" + TableAlias + ".MessageID");
                command.AddParameter(memberId);
                command.AddParameter(messageState);
            }
            List<BizMessageState> list = new List<BizMessageState>();
            DataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                BizMessageState state = CreateFromReader(reader);
                BizMessage msg = SqlBizMessageProvider.CreateFromReader(reader);
                state.Message = msg;
                list.Add(state);

            }
            reader.Close();
            command.Dispose();
            return list;
        }
    }
}
